package com.paipaideli.ui.mine.order;

import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jakewharton.rxbinding2.view.RxView;
import com.paipaideli.MyApplication;
import com.paipaideli.R;
import com.paipaideli.common.base.BasePresenterActivity;
import com.paipaideli.common.http.Api;
import com.paipaideli.common.pullrefresh.TStatusView;
import com.paipaideli.common.utils.DateUtil;
import com.paipaideli.common.utils.ImageUtil;
import com.paipaideli.common.utils.StringUtil;
import com.paipaideli.common.utils.ToastUtil;
import com.paipaideli.ui.mine.address.AddAddressActivity;
import com.paipaideli.ui.mine.head.CashActivity;
import com.paipaideli.ui.mine.safety.MyBankActivity;
import com.paipaideli.ui.pay.PayActivity;
import com.paipaideli.ui.product.ProductDetailActivity;

import org.json.JSONObject;

import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.android.schedulers.AndroidSchedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * Created by 订单详情
 */
public class OrderDetailActivity extends BasePresenterActivity {

    Unbinder unbinder;
    @BindView(R.id.top_back)
    RelativeLayout top_back;
    @BindView(R.id.top_title)
    TextView top_title;
    @BindView(R.id.tv_orderdetail_status)
    TextView tvOrderdetailStatus;
    @BindView(R.id.tv_orderdetail_qxdd)
    TextView tvOrderdetailQxdd;
    @BindView(R.id.tv_orderdetail_wlzt)
    TextView tvOrderdetailWlzt;
    @BindView(R.id.lin_orderdetail_wl)
    LinearLayout linOrderdetailWl;
    @BindView(R.id.tv_orderdetail_shname)
    TextView tvOrderdetailShname;
    @BindView(R.id.tv_orderdetail_shadd)
    TextView tvOrderdetailShadd;
    @BindView(R.id.lin_orderdetail_addok)
    LinearLayout linOrderdetailAddok;
    @BindView(R.id.lin_orderdetail_addon)
    LinearLayout linOrderdetailAddon;
    @BindView(R.id.tv_orderdetail_gys)
    TextView tvOrderdetailGys;
    @BindView(R.id.im_orderdetail_img)
    ImageView imOrderdetailImg;
    @BindView(R.id.tv_orderdetail_goodname)
    TextView tvOrderdetailGoodname;
    @BindView(R.id.tv_orderdetail_cjprice)
    TextView tvOrderdetailCjprice;
    @BindView(R.id.tv_orderdetail_yf)
    TextView tvOrderdetailYf;
    @BindView(R.id.tv_orderdetail_zjprice)
    TextView tvOrderdetailZjprice;
    @BindView(R.id.tv_orderdetail_id)
    TextView tvOrderdetailId;
    @BindView(R.id.tv_orderdetail_cjsj)
    TextView tvOrderdetailCjsj;
    @BindView(R.id.tv_orderdetail_zfsj)
    TextView tvOrderdetailZfsj;
    @BindView(R.id.btn_detail_pay)
    Button btnDetailPay;
    @BindView(R.id.lin_orderdetail_btn)
    LinearLayout lin_orderdetail_btn;
    @BindView(R.id.lin_orderdetail_into)
    LinearLayout lin_orderdetail_into;
    @BindView(R.id.bg_statusview)
    TStatusView bg_statusview;

    private String orderId;
    private String goodId;
    private String add;
    private String status;
    private String logisticCode;


    @Override
    public int getContentView() {
        return R.layout.activity_orderdetail;
    }

    @Override
    public void initView() {
        unbinder = ButterKnife.bind(this);
        top_title.setText("订单详情");

        orderId = getIntent().getStringExtra("orderId");

        //返回
        top_back.setOnClickListener(o ->
                finish()
        );

        //付款
        addDisposable(RxView.clicks(btnDetailPay)
                .throttleFirst(1, TimeUnit.SECONDS)
                .subscribe(o -> {
                    if (status.equals("1")) {//付款
                        if (add != null && !StringUtil.isEmpty(add)) {
                            MyApplication.isAlipay = 3;
                            Intent intent = new Intent(OrderDetailActivity.this, PayActivity.class);
                            intent.putExtra("which", "1");
                            intent.putExtra("orderId", orderId);
                            startActivity(intent);
                        } else {
                            ToastUtil.show("当前还未设置收货地址，请添加收货地址！");
                        }
                    } else if (status.equals("2")) {//发货
                        remind();
                    } else {//收货
                        receive();
                    }
                }));

        //物流信息查看
        addDisposable(RxView.clicks(linOrderdetailWl)
                .throttleFirst(1, TimeUnit.SECONDS)
                .subscribe(o -> {
                    if (!TextUtils.isEmpty(logisticCode)) {
                        Intent intent = new Intent(OrderDetailActivity.this, LogisticsActivity.class);
                        intent.putExtra("orderId", orderId);
                        startActivity(intent);
                    } else {
                        ToastUtil.show("暂无物流信息");
                    }

                }));

        //商品详情
        addDisposable(RxView.clicks(lin_orderdetail_into)
                .throttleFirst(1, TimeUnit.SECONDS)
                .subscribe(o -> {
                    ProductDetailActivity.open(OrderDetailActivity.this, goodId, "2");
                }));

        //收货地址
        addDisposable(RxView.clicks(linOrderdetailAddon)
                .throttleFirst(1, TimeUnit.SECONDS)
                .subscribe(o -> {
                    if (status.equals("1")) {
                        Intent intent = new Intent(OrderDetailActivity.this, AddAddressActivity.class);
                        intent.putExtra("which", "1");
                        startActivityForResult(intent, 1);
                    }
                }));

        //收货地址
        addDisposable(RxView.clicks(linOrderdetailAddok)
                .throttleFirst(1, TimeUnit.SECONDS)
                .subscribe(o -> {
                    if (status.equals("1")) {
                        Intent intent = new Intent(OrderDetailActivity.this, AddAddressActivity.class);
                        intent.putExtra("which", "1");
                        startActivityForResult(intent, 1);
                    }
                }));
    }


    @Override
    protected void onStart() {
        super.onStart();
        bg_statusview.showLoading();
        initDate();
    }

    //提醒发货
    private void remind() {
        bg_statusview.showLoading();
        JSONObject requestData = new JSONObject();
        try {
            requestData.put("id", orderId);
        } catch (Exception e) {
            e.getMessage();
        }
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), requestData.toString());
        Api.getInstanceGson().remind(body)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(request -> {
                    bg_statusview.finish();
                    if (request.getCode().equals("200")) {
                        ToastUtil.show("操作成功");
                        initDate();
                    } else {
                        ToastUtil.show(request.getMessage());
                    }
                }, throwable -> {
                    bg_statusview.finish();
                    Log.e(TAG, "error", throwable);
                });
    }

    //确认收货
    private void receive() {
        bg_statusview.showLoading();
        JSONObject requestData = new JSONObject();
        try {
            requestData.put("id", orderId);
        } catch (Exception e) {
            e.getMessage();
        }
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), requestData.toString());
        Api.getInstanceGson().receive(body)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(request -> {
                    if (request.getCode().equals("200")) {
                        ToastUtil.show(request.getMessage());
                        initDate();
                    } else {
                        ToastUtil.show(request.getMessage());
                    }
                }, throwable -> {
                    bg_statusview.finish();
                    Log.e(TAG, "error", throwable);
                });
    }

    private void initDate() {
        JSONObject requestData = new JSONObject();
        try {
            requestData.put("id", orderId);
        } catch (Exception e) {
            e.getMessage();
        }
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), requestData.toString());
        Api.getInstanceGson().orderDetail(body)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(request -> {
                    bg_statusview.finish();
                    if (request.code.equals("200")) {
                        status = request.data.status;
                        logisticCode = request.data.logisticCode;

                        if (status.equals("1")) {
                            tvOrderdetailStatus.setText("待付款");
                            lin_orderdetail_btn.setVisibility(View.VISIBLE);
                            btnDetailPay.setText("待付款");
                            tvOrderdetailWlzt.setText("订单提交成功，等待卖家付款");
                        } else if (status.equals("2")) {
                            tvOrderdetailStatus.setText("等待卖家发货");
                            lin_orderdetail_btn.setVisibility(View.VISIBLE);
                            btnDetailPay.setText("提醒发货");
                            tvOrderdetailQxdd.setVisibility(View.GONE);
                            tvOrderdetailWlzt.setText("订单付款成功，等待卖家发货");
                        } else if (status.equals("3")) {
                            tvOrderdetailStatus.setText("等待买家收货");
                            lin_orderdetail_btn.setVisibility(View.VISIBLE);
                            btnDetailPay.setText("确认收货");
                            tvOrderdetailQxdd.setVisibility(View.GONE);
                            tvOrderdetailWlzt.setText("卖家发货成功，等待买家收货");
                        } else if (status.equals("4")) {
                            tvOrderdetailStatus.setText("订单已完成");
                            lin_orderdetail_btn.setVisibility(View.GONE);
                            tvOrderdetailQxdd.setVisibility(View.GONE);
                            tvOrderdetailWlzt.setText("买家收货成功，订单已完成");
                        } else {
                            tvOrderdetailStatus.setText("订单已失效");
                            lin_orderdetail_btn.setVisibility(View.GONE);
                            tvOrderdetailQxdd.setVisibility(View.GONE);
                            tvOrderdetailWlzt.setText("订单已失效");
                        }
                        add = request.data.address;
                        if (add != null && !StringUtil.isEmpty(add)) {
                            linOrderdetailAddok.setVisibility(View.VISIBLE);
                            linOrderdetailAddon.setVisibility(View.GONE);
                            tvOrderdetailShname.setText("收货人：" + request.data.name + "     " + request.data.phone);
                            tvOrderdetailShadd.setText("收货地址：" + request.data.address);
                        } else {
                            linOrderdetailAddok.setVisibility(View.GONE);
                            linOrderdetailAddon.setVisibility(View.VISIBLE);
                        }
                        goodId = request.data.auctionInfoId;
                        tvOrderdetailGys.setText(request.data.supplierName);
                        ImageUtil.displayImage(request.data.goodsImg, imOrderdetailImg);
                        tvOrderdetailGoodname.setText(request.data.goodsName);
                        tvOrderdetailCjprice.setText("成交价：￥" + request.data.price);
                        tvOrderdetailYf.setText("运费：￥" + request.data.freight);
                        double zj = Double.valueOf(request.data.price) + Double.valueOf(request.data.freight);
                        tvOrderdetailZjprice.setText("共计：￥" + String.format("%.2f", zj) + "");
                        tvOrderdetailId.setText(request.data.no);
                        tvOrderdetailCjsj.setText(DateUtil.getDateToString(request.data.createTime));
                    } else {
                        ToastUtil.show(request.msg);
                    }
                }, throwable -> {
                    bg_statusview.finish();
                    Log.e(TAG, "error", throwable);
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            switch (requestCode) {
                case 1:
                    Bundle bundle = data.getExtras();
                    String addId = bundle.getString("addId");
                    madifyOrderAdd(addId, orderId);
                    break;
            }
        }
    }

    //修改订单收货地址
    private void madifyOrderAdd(String addId, String orderId) {
        bg_statusview.showLoading();
        JSONObject requestData = new JSONObject();
        try {
            requestData.put("addrId", addId);
            requestData.put("orderId", orderId);
        } catch (Exception e) {
            e.getMessage();
        }
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), requestData.toString());
        Api.getInstanceGson().addChange(body)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(request -> {
                    bg_statusview.finish();
                    if (request.getCode().equals("200")) {
                        initDate();
                        ToastUtil.show(request.getMessage());
                    } else {
                        ToastUtil.show(request.getMessage());
                    }
                }, throwable -> {
                    bg_statusview.finish();
                    Log.e(TAG, "error", throwable);
                });
    }
}
